<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\DistributeTask;
use app\admin\model\Article;
use app\admin\model\ShopTaskDrafts;
use app\admin\model\ShopPriceLog;
use app\admin\model\UserCoupon;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\admin\model\Shop as ShopModer;
use app\admin\model\ShopOrder;
use think\Exception;
use fast\Random;
use think\Db;

class Shop extends Api
{
    protected $NeedLogin = ['question']; //存在则不验证token
    protected $shop = [];

    public function _initialize(){
	    $action = request()->action();
		if(!in_array($action,$this->NeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
            if($this->user['status'] != 1){
                $this->error('账号异常');
            }
            $this->shop=ShopModer::where(['user_id'=>$this->user['id'],'status'=>1])->find();
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}
    //设置发放任务类型
    public function task_set(){
        $shop_id = $this->request->request('shop_id',0);
        $task_status = $this->request->request('task_status',0);

        if(!$shop_id) $this->error('商户信息错误');
        if(!$task_status) $this->error('发放任务类型错误');

        $res = ShopModer::where(['id'=>$shop_id])->update(['task_status'=>$task_status]);
        if($res){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }


    }

    //获取商户规则
    public function question(){
        $type = $this->request->request('type',4);
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',20);
        if($type == 4){
            $where=array('type'=>$type,'status'=>1);
            $list=Article::where($where)->order('ord asc')->limit(($page-1)*$pagesize,$pagesize)->select();
            foreach($list as $a=>&$b){
                $b['content']=htmlspecialchars_decode($b['content']);
            }
            $this->success('获取成功',$list);
        }else{
            $where=array('type'=>$type,'status'=>1);
            $info=Article::where($where)->find();
            if($info){
                $this->success('获取成功',$info['content']);
            }else{
                $this->error('无数据');
            }
        }
        
    }

    public function getShopTaskData(){
        if(!$this->shop){
            $this->error('数据错误');
        }
        $time =  $this->request->request('time','');
        if($time){
            $time = strtotime($time);
            $time1 = $time + 86400;
            $where = ['add_time' => ['between', [$time, $time1]],'shop_id'=>$this->shop['id']];
            $where1 = ['add_time' => ['<', $time],'shop_id'=>$this->shop['id']];
            $info['day_ft'] = DistributeTask::where($where)->count();
            $info['zong_ft'] = DistributeTask::where($where1)->count();
            $info['day_bg'] = DistributeTask::where($where)->sum('statistics_num');
            $info['zong_bg'] = DistributeTask::where($where1)->sum('statistics_num');

        }else{
            $info['day_ft'] = DistributeTask::where(['shop_id'=>$this->shop['id']])->whereTime('add_time', 'yesterday')->count();
            $info['zong_ft'] = DistributeTask::where(['shop_id'=>$this->shop['id']])->count();
            $info['day_bg'] = DistributeTask::where(['shop_id'=>$this->shop['id']])->whereTime('add_time', 'yesterday')->sum('statistics_num');
            $info['zong_bg'] = DistributeTask::where(['shop_id'=>$this->shop['id']])->sum('statistics_num');
        }
        $this->success('获取成功',$info);
    }
    

    //成为代理商
    public function add_agent(){
        $name = $this->request->request('name','');
        $phone = $this->request->request('phone','');
        $industry = $this->request->request('industry','');

        if(!$name) $this->error('姓名不可为空');
        if(!$phone) $this->error('手机号');
       
        if($this->user['is_agent'] != 0){
            $this->error('代理商状态错误,请联系管理员');
        }
        $arr = [
            'is_agent'=>1,
            'agent_text'=>json_encode(['name'=>$name,'phone'=>$phone,'industry'=>$industry]),
        ];
        $res = User::where(['id'=>$this->user['id']])->update($arr);
        if($res){
            $this->success('申请审核中');
        }else{
            $this->error('操作失败');
        }
    }
    
    
    //新增商户
    public function add_shop(){
        $imgs = $this->request->request('imgs','');
        $name = $this->request->request('name','');
        $address = $this->request->request('address','');
        $industry = $this->request->request('industry','');
        $category_id = $this->request->request('category_id',0);
        $task_status = $this->request->request('task_status',1);

        if(!$name) $this->error('商家姓名错误');
        if(!$address) $this->error('地址错误');
        //if(!$industry) $this->error('所属行业错误');
        if(!$imgs) $this->error('营业执照不可为空');
        if(!$task_status) $this->error('发放任务类型错误');
        //查询商户名称
        $info = ShopModer::where(['name'=>$name,'status'=>['neq',-1]])->value('name');
        if($info){
            $this->error('该商户名已被注册,请重新输入');
        }

        
       

        
        $info = ShopModer::where(['user_id'=>$this->user['id'],'status'=>['neq',-1]])->find();
        if($info){
            if(!$info['name']){
                //创建后台admin账号
                $salt = Random::alnum();
                //创建admin账号
                $admin = [
                    'username'=>$name,
                    'nickname'=>$name,
                    'salt'=>$salt,
                    'password'=>md5(md5(123456) . $salt),
                    'avatar'=>'/assets/img/avatar.png',
                ];
                $admin_id = Admin::insertGetId($admin);
                AuthGroupAccess::insert(['uid'=>$admin_id,'group_id'=>6]);
                $arr = [
                    'admin_id' => $admin_id,
                    'task_status' => $task_status,
                    'address' => $address,
                    'industry' => $industry,
                    'category_id' => $category_id,
                    'imgs' => $imgs,
                    'name' => $name,
                ];
                $res = ShopModer::where(['id'=>$info['id']])->update($arr);
            }else{
                $this->error('请勿重复申请');
            }
        }else{
            //创建后台admin账号
            $salt = Random::alnum();
            //创建admin账号
            $admin = [
                'username'=>$name,
                'nickname'=>$name,
                'salt'=>$salt,
                'password'=>md5(md5(123456) . $salt),
                'avatar'=>'/assets/img/avatar.png',
            ];
            $admin_id = Admin::insertGetId($admin);
            AuthGroupAccess::insert(['uid'=>$admin_id,'group_id'=>6]);
            $arr = [
                'name'=>$name,
                'imgs'=>$imgs,
                'category_id'=>$category_id,
                'industry'=>$industry,
                'address'=>$address,
                'task_status'=>$task_status,
                'add_time'=>time(),
                'user_id'=>$this->user['id'],
                'status'=>1,
                'admin_id'=>$admin_id
            ];
            $res = ShopModer::insert($arr);
        }
        if($res){
            $this->success('申请审核中');
        }else{
            $this->error('操作失败');
        }
    }

    //获取商户信息
    public function getShop(){
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }

        $shop['nickname'] = $this->user['nickname'];

        $this->success('操作成功',$shop);
    }

    //获取余额资金明细
    public function get_shop_price_log(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $month = $this->request->request('month','');

        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }

        $start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));
        $rose['yue']=$shop['balance'];
		$rose['month_in']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['>',0],'type'=>2,'consumption_type'=>1))->sum('price');	
		$rose['month_out']=0-ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['<',0],'type'=>1,'is_freeze'=>0,'freeze_type'=>0,'consumption_type'=>1))->sum('price');	
		$rose['month_log']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$add_time,'consumption_type'=>1))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as &$v){
			$v['add_time']=date("Y-m-d H:i:s",$v['add_time']);
            $v['status'] = 1;
            if($v['type'] == 1){
                if($v['is_freeze'] == 1){
                    $v['content'] = '余额冻结';
                }else{
                    $v['content'] = '余额支出';
                }
               
            }elseif($v['type'] == 2){
                $v['content'] = '余额充值';
            }elseif($v['type'] == 3){
                $v['content'] = '余额解冻';
            }
		}
        $this->success('操作成功',$rose);
    }

    //获取套餐明细
    public function get_shop_meal_log(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $month = $this->request->request('month','');

        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }

        $start_time=strtotime($month.'-01');
		$end_time=strtotime($month.'-01 +1 month');
		$add_time=array('between',array($start_time,$end_time));
        $thismonth_1=strtotime(date("Y-m-01 00:00:01"));
		$thismonth_2=strtotime('+1 month',$thismonth_1);
        $thismonth=array('between',array($thismonth_1,$thismonth_2));
        $rose['yue']=$shop['monthly_num']+$shop['thirdpartnar_num']+$shop['enemy_num']+$shop['comment_num'];
		$rose['month_in']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['>',0],'type'=>2))->sum('price');	
		$rose['month_out']=0-ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$thismonth,'price'=>['<',0],'type'=>1,'is_freeze'=>0,'freeze_type'=>0))->sum('price');	
		$rose['month_log']=ShopPriceLog::where(array('user_id'=>$this->user['id'],'add_time'=>$add_time))->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
		foreach($rose['month_log'] as &$v){
			$v['add_time']=date("Y-m-d H:i:s",$v['add_time']);
            $v['status'] = 1;
            if($v['type'] == 1){
                if($v['is_freeze'] == 1){
                    $v['content'] = '套餐冻结';
                }else{
                    $v['content'] = '套餐支出';
                }
               
            }elseif($v['type'] == 2){
                $v['content'] = '购买套餐';
            }elseif($v['type'] == 3){
                $v['content'] = '套餐解冻';
            }
            $v['price'] = $v['price']*1;
		}
        $this->success('操作成功',$rose);
    }

    //商户发布任务
    public function shop_add_task(){
        $id = $this->request->request('id','');
        $type = $this->request->request('type',1);
        $title = $this->request->request('title','');
        $content = $this->request->request('content','');
        $imgs = $this->request->request('imgs','');
        $task_type = $type = 1;//? 1 : 4;
        if(!$title){
            $this->error('请输入标题');
        }
        if(!$content){
            $this->error('请输入内容');
        }
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }
        //查看用户账号余额  固定价格冻结5元 浏览量价格冻结7元
        if($shop['task_status'] == 1){
            $task_unit_price = $shop['fixed_price'];
            $task_status = 'dianshiju';
        }
        $leixing = 1;
        if($shop['enemy_num'] == 0 && $shop['monthly_num'] == 0 && $shop['thirdpartnar_num']==0 && $task_type == 1){
            if($shop['balance'] < $task_unit_price && !$id){
                $this->error('账号余额不足');
            }
            $leixing = 2;
        }
        /* elseif(!$shop['comment_num'] && ($task_type == 4 || $task_type == 5)){
            if($shop['balance'] < 1 && !$id){
                $this->error('账号余额不足');
            }
            $leixing = 2;
        } */
        Db::startTrans();
        try {
            $arr = [
                'title'=>$title,
                'content'=>$content,
                'imgs'=> $imgs,
                'task_type'=>$task_type,
                'type'=>$shop['name'],
                'category'=>$shop['name'],
                'character_type'=>1,
                'status'=>-3,
                'shop_id'=>$shop['id']
            ];
            
            if($id){
                $info = DistributeTask::where(['id'=>$id,'status'=>-3])->find();
                if(!$info){
                    Db::rollback();
                    $this->error('当前任务状态不可编辑');
                }
                $res = DistributeTask::where(['id'=>$id])->update($arr);
            }else{
                $consumption_type = 1;
                if($leixing == 1){  //套餐消费
                   
                    $task_unit_price = 1;
                    if($task_type == 1){
                        if($shop['enemy_num']>0){
                            $consumption_type = 2;
                            $data = ['enemy_num'=>$shop['enemy_num']-$task_unit_price];
                            $arr['task_status'] = 'enemy_num';
                        }elseif($shop['monthly_num']>0){
                            $consumption_type = 4;
                            $data = ['monthly_num'=>$shop['monthly_num']-$task_unit_price];
                            $arr['task_status'] = 'monthly_num';
                        }elseif($shop['thirdpartnar_num']>0){
                            $consumption_type = 3;
                            $data = ['thirdpartnar_num'=>$shop['thirdpartnar_num']-$task_unit_price];
                            $arr['task_status'] = 'thirdpartnar_num';
                        }
                    }elseif($task_type == 4){  //评论
                        if($shop['comment_num']>0){
                            $consumption_type = 5;
                            $data = ['comment_num'=>$shop['comment_num']-$task_unit_price];
                            $arr['task_status'] = 'comment_num';
                        }
                    }
                }else{   //余额消费
                    if($type == 1){
                        $arr['task_status'] = $task_status;
                    }elseif($type == 2){
                        $arr['task_status'] = 'pinglun';
                        $task_unit_price =1;
                    }
                    $data = ['balance'=>$shop['balance']-$task_unit_price];
                }
                $arr['add_time'] = time();
                $id = DistributeTask::insertGetId($arr);
                //冻结商户金额
                $arr = [
                    'user_id'=>$shop['user_id'],
                    'shop_id'=>$shop['id'],
                    'task_id'=>$id,
                    'is_freeze'=>1,
                    'price'=>$task_unit_price*-1,
                    'type'=>1,
                    'add_time'=>time(),
                    'consumption_type'=>$consumption_type
                ];
                
                ShopPriceLog::insert($arr);
                //扣除用户账号金额
                $res = ShopModer::where(['id'=>$shop['id']])->update($data);
                //商户资金变动日志
                add_shop_balance_log($shop['id'],$task_unit_price,$shop['balance'],1);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($res){
            $this->success('发布成功');
        }else{
            $this->error('发布失败');
        }
    }
    //html_entity_decode  PHP解析JSON.stringify传递的参数 json_decode(html_entity_decode($info),true);
    //商户发布任务
    public function more_shop_add_task(){
        $id = $this->request->request('id','');
        $info = $this->request->request('info','');
        $type = $this->request->request('type',1);
        $title = $this->request->request('title','');
        $content = $this->request->request('content','');
        $imgs = $this->request->request('imgs','');
        $task_type = $type = 1 ;//? 1 : 4;
        
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('操作错误');
        }
        //查看用户账号余额  固定价格冻结5元 浏览量价格冻结7元
        if($shop['task_status'] == 1){
            $task_unit_price = $shop['fixed_price'];
            $task_status = 'dianshiju';
        }else{
            $task_unit_price = 7;
            $task_status = 'shanghu_user';
        }
        $leixing = 1;
        if(!$shop['enemy_num'] && !$shop['monthly_num'] && !$shop['thirdpartnar_num'] && $task_type == 1){
            if($shop['balance'] < $task_unit_price   && !$id){
                $this->error('账号余额不足');
            }
            $leixing = 2;
        }elseif(!$shop['comment_num'] && $task_type == 4){
            if($shop['balance'] < 1 && !$id){
                $this->error('账号余额不足');
            }
            $leixing = 2;
        }
        Db::startTrans();
        try {
            if($id){
                $arr = [
                    'title'=>$title,
                    'content'=>$content,
                    'imgs'=> $imgs,
                    'task_type'=>$task_type,
                    'type'=>$shop['name'],
                    'category'=>$shop['name'],
                    'character_type'=>1,
                    'status'=>-3,
                    'shop_id'=>$shop['id']
                ];

                $info = DistributeTask::where(['id'=>$id,'status'=>-3])->find();
                if(!$info){
                    Db::rollback();
                    $this->error('当前任务状态不可编辑');
                }
                $res = DistributeTask::where(['id'=>$id])->update($arr);
            }else{
                $is = 0;
                $info = json_decode(html_entity_decode(str_replace('\\\n','',$info)),true);
                foreach ($info as &$v) {
                    $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
                    //查看用户账号余额  固定价格冻结5元 浏览量价格冻结7元
                    if($shop['task_status'] == 1){
                        $task_unit_price = $shop['fixed_price'];
                        $task_status = 'dianshiju';
                    }else{
                        $task_unit_price = 7;
                        $task_status = 'shanghu_user';
                    }
                    $leixing = 1;
                    if(!$shop['enemy_num'] && !$shop['monthly_num'] && !$shop['thirdpartnar_num'] && $task_type == 1){
                        if($shop['balance'] < $task_unit_price   && !$id){
                            continue;
                        }
                        $leixing = 2;
                    }elseif(!$shop['comment_num'] && $task_type == 4){
                        if($shop['balance'] < 1 && !$id){
                            continue;
                        }
                        $leixing = 2;
                    }
                    if(!$v['title'] || !$v['content'] || !$v['img']){
                        continue;
                    }
                    $img = '';
                    foreach ($v['img'] as $is=>&$vs){
                        if($is == 0){
                            $img = $vs;
                        }else{
                            $img .= ','.$vs;
                        }
                    }
                    $arr = [
                        'title'=>$v['title'],
                        'content'=>$v['content'],
                        'imgs'=> $img,
                        'task_type'=>$task_type,
                        'type'=>$shop['name'],
                        'category'=>$shop['name'],
                        'character_type'=>1,
                        'status'=>-3,
                        'shop_id'=>$shop['id']
                    ];
                    if($leixing == 1){  //套餐消费
                        $task_unit_price = 1;
                        if($task_type == 1){
                            if($shop['enemy_num']>0){
                                $consumption_type = 2;
                                $data = ['enemy_num'=>$shop['enemy_num']-$task_unit_price];
                                $arr['task_status'] = 'enemy_num';
                            }elseif($shop['monthly_num']>0){
                                $consumption_type = 4;
                                $data = ['monthly_num'=>$shop['monthly_num']-$task_unit_price];
                                $arr['task_status'] = 'monthly_num';
                            }elseif($shop['thirdpartnar_num']>0){
                                $consumption_type = 3;
                                $data = ['thirdpartnar_num'=>$shop['thirdpartnar_num']-$task_unit_price];
                                $arr['task_status'] = 'thirdpartnar_num';
                            }
                        }elseif($task_type == 4){  //评论
                            if($shop['comment_num']>0){
                                $consumption_type = 5;
                                $data = ['comment_num'=>$shop['comment_num']-$task_unit_price];
                                $arr['task_status'] = 'comment_num';
                            }
                        }
    
                    }else{   //余额消费
                        if($type == 1){
                            $arr['task_status'] = $task_status;
                        }elseif($type == 2){
                            $arr['task_type'] = 4;
                            $arr['task_status'] = 'pinglun';
                            $task_unit_price = 1;
                        }
                        $consumption_type = 1;
                        $data = ['balance'=>$shop['balance']-$task_unit_price];
                    }
                    $arr['add_time'] = time();
                    $id = DistributeTask::insertGetId($arr);
                    //冻结商户金额
                    $arr = [
                        'user_id'=>$shop['user_id'],
                        'shop_id'=>$shop['id'],
                        'task_id'=>$id,
                        'is_freeze'=>1,
                        'price'=>$task_unit_price*-1,
                        'type'=>1,
                        'add_time'=>time(),
                        'consumption_type'=>$consumption_type
                    ];
                    
                    ShopPriceLog::insert($arr);
                    //扣除用户账号金额
                    $res = ShopModer::where(['id'=>$shop['id']])->update($data);
                    //商户资金变动日志
                    add_shop_balance_log($shop['id'],$task_unit_price,$shop['balance'],1);
                    $is = 1;
                }

               if($is == 0){
                    $this->error('发布失败');
               }

                
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($res){
            $this->success('发布成功');
        }else{
            $this->error('发布失败');
        }
    }


    
    //获取我的任务列表
    public function getShopList(){
        $page = $this->request->request('page',1);
        $time = $this->request->request('time','');
        $pagesize = $this->request->request('pagesize',10);
        $task_index = $this->request->request('task_index',1);  //1待审核   2待接单   3已接单  4已结算
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('商家状态错误');
        }
        $where = [
            'type'=>$shop['name']
        ];
        if($task_index == 1){
            $where['status'] = -3;
        }elseif($task_index == 2){
            $where['status'] = 0;
        }elseif($task_index == 3){
            $where['status'] = ['in',[1,2,-1]];
        }elseif($task_index == 4){
            $where['status'] = 3;
        }
        if($time){
            $time = strtotime($time);
            $where['add_time'] = ['<',$time];
        }

        $list = DistributeTask::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        foreach ($list as &$v) {
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['complete_time'] = date('Y-m-d H:i:s',$v['complete_time']);
            $v['receive_time'] = date('Y-m-d H:i:s',$v['receive_time']);

            if($v['status'] == -3){
                $v['statusName'] = '待审核';
            }elseif($v['status'] == -2){
                $v['statusName'] = '已退回';
            }elseif($v['status'] == 0){
                $v['statusName'] = '待接单';
            }elseif($v['status'] == 1 || $v['status'] == 2 || $v['status'] == -1){
                $v['statusName'] =  '已接单';
            }elseif($v['status'] == 3){
                $v['statusName'] = '已完成';
            }
            if(!$v['imgs']){
                $v['imgs'] = 'https://oa.yuxiang123.cn/uploads/img/zwtp.svg';
            }
        }
        
        $this->success('获取成功',$list);
    }
    //获取我的草稿详情
    public function getTaskDrafts(){
        $id = $this->request->request('id',0);
        $info =  ShopTaskDrafts::where(['id'=>$id])->find();
        if(!$info){
            $this->error('参数错误');
        }
        $info['imgs_arr'] = explode(',',$info['imgs']);
        //内容里面  话题和内容区分开
        $content = $info['content'];
        if (strpos($content, '#') !== false) {
            $info['content'] =  substr($content,0,strpos($content, '#'));
            $info['topic'] =  substr($content,strpos($content, '#'));
        }else{
            $info['topic'] = '';
        }
       
        $this->success('操作成功',$info);
    }
    //获取草稿列表
    public function getDraftsList(){
        $page = $this->request->request('page',1);
        $pagesize = $this->request->request('pagesize',10);
        $shop = ShopModer::where(['user_id'=>$this->user['id']])->find();
        if(!$shop){
            $this->error('商家状态错误');
        }
        $where = [
            'status'=>1,
            'shop_id'=>$this->shop['id']
        ];
        $list = ShopTaskDrafts::where($where)->order('add_time desc')->limit(($page-1)*$pagesize,$pagesize)->select();
        foreach ($list as &$v) {
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if($v['imgs']){
                $imgs = explode(',',$v['imgs']);
                $v['img'] = $imgs[0];
            }else{
                $v['img'] = 'https://oa.yuxiang123.cn/assets/task/shop/wu.svg';
            }
        }
        $this->success('获取成功',$list);
    }
    //删除草稿
    public function delDrafts(){
        $id = $this->request->request('id','');
        if(!$id){
            $this->error('操作失败');
        }
        $res = ShopTaskDrafts::where(['id'=>$id,'shop_id'=>$this->shop['id']])->update(['status'=>-1]);
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    //获取自己今日已发送
    public function send_task_sum(){
        $shop = ShopModer::where(['user_id'=>$this->user['id'],'status'=>1])->find();
        if($shop){
            $task_sum = DistributeTask::whereTime('receive_time', 'today')->where(['status'=>1,'type'=>$shop['name']])->count();
        }else{
            $task_sum = 0;
        }
        $this->success('操作成功',$task_sum);

    }


    
    //获取我的订单列表
    public function shop_order(){
        $status=$this->request->request('status','1');  //1 我买的   2我卖的
        $page=$this->request->request('page',1);
        $pagesize=$this->request->request('pagesize',10);
        $where=['a.user_id'=>$this->user['id']];
        if(isset($status) && $status != ''){
            $where['a.status'] = $status;
        }else{
            $where['a.status'] = 1;
        }
        $list=ShopOrder::alias('a')
        ->order("add_time desc")
        ->field("a.*,s.name as shop_name,u.nickname,u.mobile,u.avatar")
        ->where($where)
        ->join("shop s","s.id = a.shop_id")
        ->join("user u","u.id = a.user_id")
        ->limit(($page-1)*$pagesize,$pagesize)
        ->select();
        foreach($list as &$v){
            if($v['status'] == 0 && time()-$v['add_time'] > 900){
                //超过15分钟自动取消订单
                $v['status'] = -1;
                ShopOrder::where(['id'=>$v['id']])->update(['status'=>-1]);
                if($v['coupon_id']){
                    UserCoupon::where(['id'=>$v['coupon_id']])->update(['status'=>1]);
                }
            }
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            if($v['is_ai']){
                $v['type_name'] = 'AI套餐';
            }else{
                $v['type_name'] = '余额充值';
            }
        }
        $this->success('获取成功',$list);
    }


    //加入草稿箱
    public function addShopTaskDrafts(){
        if(!$this->shop){
            $this->error('商户信息错误');
        }
        $title = $this->request->request('title','');
        $content = $this->request->request('content','');
        $imgs = $this->request->request('imgs','');
        $arr = [
            'title'=>$title,
            'content'=>$content,
            'imgs'=>$imgs,
            'shop_id'=>$this->shop['id'],
            'add_time'=>time(),
        ];
        $res = ShopTaskDrafts::insert($arr);
        if($res){
            $this->success('操作成功');
        }else{
            $this->success('操作失败');
        }
    }
    //获取任务详情
    public function getInfo(){
        $id = $this->request->request('id',0);
        $info =  DistributeTask::where(['id'=>$id])->find();
        if(!$info){
            $this->error('参数错误');
        }
        $info['imgs_arr'] = explode(',',$info['imgs']);
        //内容里面  话题和内容区分开
        $content = $info['content'];
        if (strpos($content, '#') !== false) {
            $info['content'] =  substr($content,0,strpos($content, '#'));
            $info['topic'] =  substr($content,strpos($content, '#'));
        }else{
            $info['topic'] = '';
        }
        $this->success('操作成功',$info);
    }



    

}